<template>
	<div class="chatAppBody">
		<div class="chatElfTitle">{{entInfo.companyName}}</div>
		<div class="chatBox" @click="showEmojis=false;showExtendTool=false">
			<div class="chatElfNotice" v-if="historyList.elfMoreMessage"><a class="elfMoreMessage" @click="getHistoryList">點選加載更多記錄</a></div>
			<div v-for="row in msgList">
				<div class="chatElfNotice" v-if="row.type=='notice'">
					<div class="chatNoticeContent">{{row.content}}</div>
				</div>

				<div v-if="row.type=='message' && row.isme!=true">
					<div class="chatElfNotice" v-if="row.show_time==true">{{row.time}}</div>
					<div class="chatElfRow">
						<el-avatar class="chatAvatar" :size="30" :src="row.avator"></el-avatar>
						<div class="chatMsgContent">
							<div class="chatUsername">{{row.name}}</div>
							<div class="chatElfContent" v-html="row.content" @click="htmlBoxClick($event)"></div>
						</div>
					</div>
				</div>
				<div v-if="row.type=='message' && row.isme==true">
					<div class="chatElfNotice" v-if="row.show_time==true">{{row.time}}</div>
					<div class="chatElfRow chatElfRowMe">
						<div class="chatElfContent" v-html="row.content" @click="htmlBoxClick($event)"></div>
						<el-avatar class="chatAvatar" :size="30" :src="row.avator"></el-avatar>
					</div>
				</div>

			</div>
		</div>
		<div class="chatElfNotice" v-if="websocket.serverReturnClose"><a class="alink" @click="window.location.reload()">點選重新建立會話</a></div>
		<div class="chatBottom" v-show="!websocket.serverReturnClose">
			<div class="chatSendProduct" v-if="visitorProduct!=null">
				<img :src="visitorProduct.img" class="productImg"/>
				<div class="productInfo">
					<div>{{visitorProduct.title}}</div>
					<div class="productPrice">{{visitorProduct.price}}</div>
				</div>
				<div class="productBtns">
					<div class="el-icon-close" @click="visitorProduct=null"></div>
					<el-button size="mini" type="primary" @click="sendProductInfo">发送</el-button>
				</div>
			</div>
			<div class="hotQuestions" v-if="question.hotQuestion.length!=0">
				<a class="slideInRightItem"  v-for="row in question.hotQuestion" @click="visitor.message=row;chatToUser($event)">{{row}}</a>
			</div>
			
			<div class="emojis" v-show="showEmojis">
				<span v-for="key in emojis" @click="visitor.message+=key;showEmojis=false">{{key}}</span>
			</div>
			<div class="chatElfAreaBox">
				<div class="chatElfArea">
					<div @click="audioDialog=true" class="chatJiahaoBtn iconfont icon-mic"></div>
					<textarea class="chatElfAreaInput" v-model="visitor.message"  @keyup.ctrl.enter.exact="chatToUser($event)" @keyup.enter.exact="chatToUser($event,'enter')" ></textarea>
					<div @click="showEmojis==true?showEmojis=false:showEmojis=true"  class="chatJiahaoBtn iconfont icon-xiaolian2"></div>
					<div v-show="visitor.message==''" @click="showExtendTool==true?showExtendTool=false:showExtendTool=true;" class="iconfont icon-zengjiatianjiajiahao"></div>
					<a v-show="visitor.message!=''" @click="chatToUser($event)" class="chatSendBtn">發送</a>
				</div>
				<div class="chatElfExtend" v-show="showExtendTool">
					<div class="iconExtendBtn"  @click="uploadImg">
						<div class="elIcon el-icon-picture"></div>
						<div>圖片</div>
					</div>
					<div class="iconExtendBtn"  @click="uploadFile">
						<div  class="elIcon el-icon-upload"></div>
						<div>檔案</div>
					</div>
					<div class="iconExtendBtn" @click="callKefu('phone')">
						<div class="elIcon el-icon-phone-outline" style="font-size: 22px;"></div>
						<div>語音</div>
					</div>
					<div class="iconExtendBtn" @click="callKefu('video')">
						<div class="elIcon el-icon-video-camera" style="font-size: 22px;"></div>
						<div>視頻</div>
					</div>
				</div>
			</div>

		</div>
		<div class="videoAudioBox" v-show="peerjs.remoteVideoStream">
			<video id="remoteVideo" controls autoplay></video>
			<div class="bottomBtns">
				<a class="refuse" @click="callClose()">掛斷</a>
			</div>
		</div>
		<div class="videoAudioBox" v-show="peerjs.remoteAudioStream">
			<img id="remoteVideoMaskLogo" :src="kefu.staffAvator" />
			<div class="bottomBtns">
				<audio id="remoteAudio" controls autoplay playsinline muted></audio>
				<a class="refuse" @click="callClose();">掛斷</a>
			</div>
			
		</div>
		<!-- 大图预览 -->
		<el-image
				style="display: none;"
				ref="preview"
				class="hideImgDiv"
				:src="imgPreviewSrc[0]"
				:preview-src-list="imgPreviewSrc"
		></el-image>
		<!-- //大图预览 -->
		<!--录音-->
		<el-dialog
				:visible.sync="audioDialog"
				width="100%"
				center
		>
			<div class="dialogRecoder">
				<el-progress :color="colors" type="dashboard" :format="recoderFormat" :stroke-width="10" :percentage="recoderSecond"></el-progress>
				<br/>
				<audio v-show="recorderEnd!=null" controls ref="audio" muted="muted" src="" id="audio"></audio>
				<br/>
				<el-button @click="startRecoder()" size="small" type="primary">開始</el-button>
				<el-button @click="stopRecoder()" size="small" type="warning">結束</el-button>
				<el-button @click="cancelRecoder()" size="small" type="danger">取消</el-button>
				<el-button @click="sendRecoder()" size="small" type="success">發送</el-button>
			</div>
		</el-dialog>
		<!--//录音-->
		<!--在线评价-->
		<div v-if="comment.dialog" class="comment">
			<div class="scoreBox">
				<i class="iconfont icon-guanbi" @click="comment.dialog=false"></i>
				<el-avatar :size="80" :src="kefu.staffAvator"></el-avatar>
				<div class="scoreTitle">請您對服務進行評價</div>
				<div class="scoreDesc">您的好評是對我們最大的鼓勵 如有疑問歡迎再次咨詢</div>
				<el-rate v-model="comment.score"></el-rate>
				<el-input
				 class="commentArea"
				  type="textarea"
				  :rows="6"
				  placeholder="您還可填寫反饋（選填）"
				  v-model="comment.textarea">
				</el-input>
				<el-button @click="sendComment" :disabled="comment.score==0" class="commentBtn" type="warning" style="width: 90%;border-radius: 20px;">提交</el-button>
			</div>
		</div>
		<!--//在线评价-->


		<audio id="chatMessageAudio" style="display: none;" :src="require('@/assets/alert2.ogg')"></audio>
	</div>
</template>

<script>
	import tools from '../tools/functions.js'
	import storage from '../tools/localStorage.js'
	import xss from 'xss'
	import Recorder from 'js-audio-recorder'
	import "../tools/peer.js"
	export default {
		name: 'ChatApp',
		data() {
		  return {
			  window:window,
			  kefu:{
				  entAvator:"",
				  entName:"",
				  staffAvator:"",
				  staffName:"",
			  },
			  visitor:{
				  to_id:"",
				  visitor_id:"",
				  ent_id:"",
				  message:"",
				  avator:"",
			  },
			  peerjs:{
				  peer:null,
				  peerjsId:"",
				  localStream:null,
				  remoteAudioStream:null,
				  remoteVideoStream:null,
				  kefuPeerId:"",
				  call:null,
			  },
			  question:{
				  hotQuestion:[],
			  },
			  historyList:{
				  list:[],
				  elfMoreMessage:false,
				  page:1
			  },
			  msgList:[],
			  entInfo:{
				  companyName:"",
			  },
			  visitorProduct:null,
			  websocket:{
				  // 设置重连时间间隔（单位：毫秒）
				  RECONNECT_INTERVAL: 1000,
				  // 设置最大重连次数
				  MAX_RECONNECT_TIMES:30,
				  //重连次数
				  RECONNET_TIMES :0,
				  //ws对象
				  instance:null,
				  //服务端返回close指令
				  serverReturnClose:false,
			  },
			  showExtendTool:false,
			  //时间相关
			  timeTool:{
				  timeoutTime:20*60*1000,
				  timeoutTimer:null,
				  activeTime:Date.now(),
			  },
			  //大图预览
			  imgPreviewSrc:[""],
			  //录音
			  recorder:null,
			  audioDialog:false,
			  recoderSecond:0,
			  recorderEnd:null,
			  colors: [
				  {color: '#f56c6c', percentage: 20},
				  {color: '#e6a23c', percentage: 40},
				  {color: '#5cb87a', percentage: 60},
				  {color: '#1989fa', percentage: 80},
				  {color: '#6f7ad3', percentage: 100}
			  ],
				//评价
				comment:{
					dialog:false,
					score:0,
					textarea:"",
				},
				showEmojis:false,
				emojis:{"smile":"😄","smiley":"😃","grinning":"😀","blush":"😊","wink":"😉","heart_eyes":"😍","kissing_heart":"😘","kissing_closed_eyes":"😚","kissing":"😗","kissing_smiling_eyes":"😙","stuck_out_tongue_winking_eye":"😜","stuck_out_tongue_closed_eyes":"😝","stuck_out_tongue":"😛","flushed":"😳","grin":"😁","pensive":"😔","relieved":"😌","unamused":"😒","disappointed":"😞","persevere":"😣","cry":"😢","joy":"😂","sob":"😭","sleepy":"😪","disappointed_relieved":"😥","cold_sweat":"😰","sweat_smile":"😅","sweat":"😓","weary":"😩","tired_face":"😫","fearful":"😨","scream":"😱","angry":"😠","rage":"😡","triumph":"😤","confounded":"😖","laughing":"😆","yum":"😋","mask":"😷","sunglasses":"😎","sleeping":"😴","dizzy_face":"😵","astonished":"😲","worried":"😟","frowning":"😦","anguished":"😧","imp":"👿","open_mouth":"😮","grimacing":"😬","neutral_face":"😐","confused":"😕","hushed":"😯","smirk":"😏","expressionless":"😑","man_with_gua_pi_mao":"👲","man_with_turban":"👳","cop":"👮","construction_worker":"👷","guardsman":"💂","baby":"👶","boy":"👦","girl":"👧","man":"👨","woman":"👩","older_man":"👴","older_woman":"👵","person_with_blond_hair":"👱","angel":"👼","princess":"👸","smiley_cat":"😺","smile_cat":"😸","heart_eyes_cat":"😻","kissing_cat":"😽","smirk_cat":"😼","scream_cat":"🙀","crying_cat_face":"😿","joy_cat":"😹","pouting_cat":"😾","japanese_ogre":"👹","japanese_goblin":"👺","see_no_evil":"🙈","hear_no_evil":"🙉","speak_no_evil":"🙊","skull":"💀","alien":"👽","hankey":"💩","fire":"🔥","sparkles":"✨","star2":"🌟","dizzy":"💫","boom":"💥","anger":"💢","sweat_drops":"💦","droplet":"💧","zzz":"💤","dash":"💨","ear":"👂","eyes":"👀","nose":"👃","tongue":"👅","lips":"👄","thumbs_up":"👍","-1":"👎","ok_hand":"👌","facepunch":"👊","fist":"✊","wave":"👋","hand":"✋","open_hands":"👐","point_up_2":"👆","point_down":"👇","point_right":"👉","point_left":"👈","raised_hands":"🙌","pray":"🙏","clap":"👏","muscle":"💪","walking":"🚶","runner":"🏃","dancer":"💃","couple":"👫","family":"👪","couplekiss":"💏","couple_with_heart":"💑","dancers":"👯","ok_woman":"🙆","no_good":"🙅","information_desk_person":"💁","raising_hand":"🙋","massage":"💆","haircut":"💇","nail_care":"💅","bride_with_veil":"👰","person_with_pouting_face":"🙎","person_frowning":"🙍","bow":"🙇","tophat":"🎩","crown":"👑","womans_hat":"👒","athletic_shoe":"👟","mans_shoe":"👞","sandal":"👡","high_heel":"👠","boot":"👢","shirt":"👕","necktie":"👔","womans_clothes":"👚","dress":"👗","running_shirt_with_sash":"🎽","jeans":"👖","kimono":"👘","bikini":"👙","briefcase":"💼","handbag":"👜","pouch":"👝","purse":"👛","eyeglasses":"👓","ribbon":"🎀","closed_umbrella":"🌂","lipstick":"💄","yellow_heart":"💛","blue_heart":"💙","purple_heart":"💜","green_heart":"💚","broken_heart":"💔","heartpulse":"💗","heartbeat":"💓","two_hearts":"💕","sparkling_heart":"💖","revolving_hearts":"💞","cupid":"💘","love_letter":"💌","kiss":"💋","ring":"💍","gem":"💎","bust_in_silhouette":"👤","speech_balloon":"💬","footprints":"👣"},
		  }
		},
		methods: {
			visitorLogin(){
				var _this=this;
				let entId=tools.getQuery("ent_id");
				let toId=tools.getQuery("kefu_id");
				let visitor_name=tools.getQuery("visitor_name");
				let avator=tools.getQuery("avator");
				let visitorId=tools.getQuery("visitor_id");
				if(visitorId==""){
					visitorId=storage.getFakeCookie("visitor_"+entId);
				}
				this.visitor.ent_id=entId;
				this.$axios.post(this.ApiHost+'/2/visitorLogin', {
					ent_id:entId,
					to_id:toId,
					visitor_id:visitorId,
					visitor_name:visitor_name,
					avator:avator,
				}).then(function (response) {
					var code=response.data.code;
					var msg=response.data.msg;
					if(code!=200){
						_this.$message({
						  message: msg,
						  type: 'error'
						});
						_this.loading = _this.$loading({
							lock: true,
							text: msg,
							background: 'rgba(0, 0, 0, 0.7)'
						});
						return ;
					}
					if(response.data.alloffline){
						_this.showTitle("客服全部離線，您可能無法及時獲得回覆。");
					}
					let result=response.data.result;
					let kefu=response.data.kefu;
					_this.visitor.to_id=result.to_id;
					_this.visitor.visitor_id=result.visitor_id;
					_this.visitor.avator=tools.getImageUrl(result.avator,_this.ApiHost);
					_this.kefu.entAvator=tools.getImageUrl(kefu.avatar,_this.ApiHost);
					_this.kefu.staffAvator=tools.getImageUrl(kefu.staffAvatar,_this.ApiHost);
					if(!visitorId){
						storage.setFakeCookie("visitor_"+_this.visitor.ent_id,_this.visitor.visitor_id,response.data.visitorCookie);
					}
					//连接websocket
					_this.connect();
					//自动欢迎
					_this.getAutoWelcome();
					//展示历史消息
					_this.getHistoryList();
					//获取热门问题
					_this.getTopRequest();
					//获取扩展信息
					_this.getUrlExtra();
				}).catch(function (error) {
					_this.$message({
					  message: error.message,
					  type: 'error'
					});
				});
			},
			//获取常问关键词
			getTopRequest(){
				var _this=this;
				let entId=tools.getQuery("ent_id");
				this.$axios.get(this.ApiHost+'/2/getTopQuestion?ent_id='+entId).then(function (response) {
					let result=response.data.result;
					if(result.hotQuestion){
						let hotQuestion=result.hotQuestion.replace("，",",").split(",");
						_this.question.hotQuestion=hotQuestion;
					}

					console.log(hotQuestion);
				}).catch(function (error) {
				});
			},
			//展示自动欢迎信息
			getAutoWelcome(){
				var _this=this;
				let entId=tools.getQuery("ent_id");
				this.$axios.get(this.ApiHost+'/2/notices?ent_id='+entId+"&kefu_name="+this.visitor.to_id).then(function (response) {
					let result=response.data.result;
					let welcome=result.welcome;
					let companyName=result.username;
					_this.entInfo.companyName=companyName;
					tools.displayGreetings(welcome,function(row){
						let message={
							type:"message",
							isme:false,
							name:row.name,
							avator:tools.getImageUrl(row.avator,_this.ApiHost),
							content:row.content,
							originTime:tools.getNowDate(),
							time:tools.shortTime(tools.getNowDate())
						}
						tools.alertSound("chatMessageAudio");
						_this.msgList.push(message);
						_this.scrollBottom();
					});
					
				}).catch(function (error) {
				});
			},
			//展示历史消息记录
			getHistoryList(){
				var _this=this;
				let pagesize=5;
				_this.historyList.elfMoreMessage=false;
				this.$axios.get(this.ApiHost+'/2/messages_page',{params:{
					pagesize:5,
					ent_id:this.visitor.ent_id,
					page:this.historyList.page,
					visitor_id:this.visitor.visitor_id,
				}}).then(function (response) {
					let result=response.data.result;
					let msgList=result.list;
					if(msgList.length>=pagesize){
						_this.historyList.elfMoreMessage=true;
					}else{
						_this.historyList.elfMoreMessage=false;
					}
					for(var i=0;i<msgList.length;i++) {
						let row = msgList[i];
						if (row["mes_type"] == "kefu") {
							row.isme = false;
						} else {
							row.isme = true;
						}
						if((i+1)<msgList.length){
							const nextTime = new Date(msgList[i+1]["time"]).getTime();
							const currTime = new Date(row["time"]).getTime();
							if((currTime-nextTime)>=180000){
								row.show_time=true;
							}else{
								row.show_time=false;
							}
						}
						row.type="message";
						row.content=tools.replaceContent(row.content,_this.ApiHost);
						row.originTime = row["time"];
						row.time = tools.shortTime(row["time"]);
						row.avator=tools.getImageUrl(row.avator,_this.ApiHost);
						_this.msgList.unshift(row);
					}
					_this.historyList.page++;
				}).catch(function (error) {
				});
			},
		   //发送给客户
			chatToUser:function(e) {
				let _this=this;
				//用户点击了ctrl+enter触发
				if(e && e.ctrlKey && e.keyCode==13) { 
					this.visitor.message += '\n';
					return;
				}
				let message=xss(tools.trim(this.visitor.message.replace(/\r\n|\n/g,"<br>"),"<br>"));
				if(message=="") return;
				let sendMessage = {
					content:message,
					from_id: this.visitor.visitor_id,
					to_id:this.visitor.to_id,
				};
				let showMessage={
					type:"message",
					isme:true,
					content:tools.replaceContent(message,_this.ApiHost),
					show_time:false,
					time:tools.getNowDate(),
					originTime:tools.getNowDate(),
					avator:tools.getImageUrl(this.visitor.avator,this.ApiHost),
				}
				this.msgList.push(showMessage);
				this.scrollBottom();
				this.visitor.message="";
				this.timeTool.activeTime=Date.now();
				this.$axios.post(this.ApiHost+'/2/message',sendMessage).then(function (response) {

				}).catch(function (error) {
					_this.$message({
					  message: error.message,
					  type: 'error'
					});
				});
			},
			//处理收到消息
			receiveMessage(msg){

				let content = {
					type:"message",
					avator :tools.getImageUrl(msg.avator,this.ApiHost),
					name:msg.name,
					content:tools.replaceSpecialTag(msg.content,this.ApiHost),
					isme:false,
					time:tools.shortTime(msg.time),
					originTime:msg.time,
				}
				if(this.msgList.length>1){
				    const nextTime = new Date(this.msgList[this.msgList.length-1]["originTime"]).getTime();
				    const currTime = new Date(content.originTime).getTime();
				    if((currTime-nextTime)>=180000){
				        content.show_time=true;
				    }else{
				        content.show_time=false;
				    }
				}
				//声音通知
				tools.alertSound("chatMessageAudio");
				//桌面通知
				tools.notify(msg.name, {
					body: msg.content,
					icon: msg.avator
				},function(notification) {
					window.focus();
					notification.close();
				});
				//标题闪动
				tools.flashTitle(document.title);
				this.msgList.push(content);
				this.scrollBottom();
			},
			//滚动到底部
			scrollBottom:function(){
				var _this=this;
				this.$nextTick(function(){
					var container = _this.$el.querySelector(".chatBox");
					container.scrollTop = 999999999;
				});
			},
			/**
			 * 连接websocket
			 */
			connect () {
				var _this=this;
				let ws = new WebSocket(this.WebsocketHost+`/ws_visitor?visitor_id=${this.visitor.visitor_id}&to_id=${this.visitor.to_id}`);
				ws.onopen = function () {
					console.log('WebSocket 连接已打开');
					_this.checkTimeout();
					//_this.reconnectTimes = 0;
				};
				ws.onerror = function () {
					console.log('WebSocket 连接错误');
					// 尝试重连
					_this.reconnect();
					//关闭定时
					clearInterval(_this.timeTool.timeoutTimer);
				};
				ws.onclose = function () {
					console.log('WebSocket 连接已关闭');
					// 尝试重连
					_this.reconnect();
					//关闭定时
					clearInterval(_this.timeTool.timeoutTimer);
				};
				ws.onmessage = function (event) {
					console.log(`收到服务器的消息：${event.data}`);
					let result=event.data;
					let serverMessage=JSON.parse(result);
					let type=serverMessage.type;
					let data=serverMessage.data;
					if(type=="message"){
						_this.receiveMessage(data);
					}
					//客服评价请求
					if(type=="comment"){
						_this.comment.dialog=true;
						_this.websocket.serverReturnClose=true;
						_this.websocket.instance.close();
					}
					if(type=="close"||type=="force_close"){
						_this.comment.dialog=true;
						_this.websocket.serverReturnClose=true;
						_this.websocket.instance.close();
					}
					//客服接受通话
					if(type=="accept"){
						_this.peerjs.kefuPeerId=data;
						//访客调用客服
						_this.callPeer();
					}
					if (type == "refuse") {
						_this.$message({
							message: "客服已挂断",
							type: 'error'
						});
						_this.callClear();
					}
					//客服发送语音请求
					if(type=="callPhone"){
						_this.callKefu('phone');
					}
					if(type=="callVideo"){
						_this.callKefu('video');
					}
				};
				_this.websocket.instance=ws;
			},
			// 尝试重连
			reconnect(){
				var _this=this;
				if (_this.websocket.serverReturnClose) {
					console.log('停止重连,服务端close指令');
					return;
				}
				if (_this.websocket.RECONNET_TIMES >= _this.websocket.MAX_RECONNECT_TIMES) {
					console.log('重连失败');
					return;
				}
				_this.websocket.RECONNET_TIMES++;
				console.log(`正在尝试重连（第 ${_this.websocket.RECONNET_TIMES} 次）`);
				setTimeout(function () {
					_this.connect();
				}, _this.websocket.RECONNECT_INTERVAL); 
			},
			//获取url中的扩展信息
			getUrlExtra(){
				let extra=tools.getQuery("extra");console.log(extra);
				if(!extra) return;
				let jsonStr=tools.b64DecodeUnicode(extra);
				let extraJson=JSON.parse(jsonStr);
				this.visitorProduct=extraJson.visitorProduct;
			},
			//发送产品信息
			sendProductInfo(){
				if(this.visitorProduct==null) return;
				this.visitor.message="product["+JSON.stringify(this.visitorProduct)+"]";
				this.chatToUser();
				this.visitorProduct=null;
			},
			//语音请求
			callKefu(type){
				this.$confirm("您想要發起語音或視訊通話","通知", {
					confirmButtonText: "確認",
					cancelButtonText: "取消",
					type: 'warning'
				}).then(() => {
					var isVideo=false;
					if(type=="video"){
						isVideo=true;
					}
					var _this=this;
					let res=tools.getCompatibleUserMedia({video:isVideo, audio: {
						noiseSuppression: true,
						echoCancellation: true,
					}},function(stream) {
						_this.initPeerjs(function(peerid){
							//初始化成功
							_this.peerjs.peerjsId=peerid;
							_this.peerjs.localStream=stream;
							//请求客服发送他们的peerid过来
							_this.$axios.post(_this.ApiHost+'/2/callKefu',{"action":"callpeer",kefu_id:_this.visitor.to_id,visitor_id:_this.visitor.visitor_id});
							_this.$message({
								type: 'success',
								message: "通話請求已經發出！"
							});
						});
						_this.visitor.message="請求通話";
						_this.chatToUser();
					},function(err) {
						_this.$message({
							type: 'error',
							message: err
						});
					});
					if(!res){
						_this.$message({
							type: 'error',
							message: "Your browser does not support the getUserMedia API."
						});
					}
				});
				
			},
			//初始化peer
			initPeerjs(callback){
				let peer = new Peer();
				this.peerjs.peer=peer;
				var _this=this;
				peer.on('open', function(id) {
					console.log('My peer ID is: ' + id);
					callback(id);
				});
				peer.on('close', function() {
					console.log('My peer close');
				});
				peer.on('disconnected', function() {
					console.log('My peer disconnected');
				});
				peer.on('error', function() {
					console.log('My peer error');
				});
			},
			//call peer
			callPeer(){
				var _this=this;
				//调用请求远程客服
				let call = _this.peerjs.peer.call(_this.peerjs.kefuPeerId, _this.peerjs.localStream);
				call.on('stream', function(remoteStream) {
					console.log("call stream",remoteStream);
					var videoTracks = remoteStream.getVideoTracks();
					var audioTracks = remoteStream.getAudioTracks();
					//视频流
					if (videoTracks.length > 0) {
						console.log("客服视频接待");
						var remoteVideo = document.getElementById("remoteVideo");
						remoteVideo.srcObject = remoteStream;
						remoteVideo.play();
						_this.peerjs.remoteVideoStream=remoteStream;
					}else if (audioTracks.length > 0) {
						//音频流
						console.log("客服音频接待");
						var remoteAudio = document.getElementById("remoteAudio");
						remoteAudio.srcObject = remoteStream;
						remoteAudio.play();
						_this.peerjs.remoteAudioStream=remoteStream;
					}
				});
				call.on('close', function() {
					console.log("call close");
				});
				call.on('error', function(err) {
					console.log("call error",err);
				});
				this.peerjs.call=call;
			},
			//挂断通话
			callClose(){
				var _this=this;
				_this.$axios.post(_this.ApiHost+"/2/callKefu",{"action":"callCancel",kefu_id:_this.visitor.to_id,visitor_id:_this.visitor.visitor_id},function(result){
				});
				_this.callClear();
				_this.visitor.message="🚫 cancel";
				_this.chatToUser();
			},
			//清理call
			callClear(){
				var _this=this;
				if(_this.peerjs.call){
					_this.peerjs.call.close();
					_this.peerjs.call=null;
				} 
				if(_this.peerjs.remoteVideoStream){
					var tracks=_this.peerjs.remoteVideoStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.remoteVideoStream=null;
				}
				if(_this.peerjs.remoteAudioStream){
					var tracks=_this.peerjs.remoteAudioStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.remoteAudioStream=null;
				}
				if(_this.peerjs.localStream){
					var tracks=_this.peerjs.localStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.localStream=null;
				}
			},
			//上传图片
			uploadImg:function (){
				let _this=this;
				let input = document.createElement("input");
				input.type = "file";
				input.accept = "image/gif,image/jpeg,image/jpg,image/png";
				input.style.display = "none";
				input.addEventListener("change", function(e) {
				let formData = new FormData();
				let file = e.target.files[0];
				formData.append("imgfile", file); //传给后台的file的key值是可以自己定义的
				fetch(_this.ApiHost+'/uploadimg', {
				  method: "POST",
				  body: formData
				})
				.then(response => response.json())
				.then(res => {
				  console.log(res);
					if(res.code!=200){
					  _this.$message({
						  message: res.msg,
						  type: 'error'
					  });
					}else{
					  _this.$message({
						  message: "success！",
						  type: 'success'
					  });
					  _this.visitor.message='img[' + res.result.path + ']';
					  _this.chatToUser();
					  setTimeout(function () {
						  _this.scrollBottom();
					  },2000);
					}
				})
				.catch(error => {
				  console.error(error);
				});
				});
				document.body.appendChild(input);
				input.click();
			},
			//上传文件
			uploadFile:function (){
				let _this=this;
				let input = document.createElement("input");
				input.type = "file";
				input.style.display = "none";
				input.addEventListener("change", function(e) {
				let formData = new FormData();
				let file = e.target.files[0];
				formData.append("realfile", file); //传给后台的file的key值是可以自己定义的
				fetch(_this.ApiHost+'/2/uploadFile', {
				  method: "POST",
				  body: formData
				})
				.then(response => response.json())
				.then(res => {
				  console.log(res);
					if(res.code!=200){
					  _this.$message({
						  message: res.msg,
						  type: 'error'
					  });
					}else{
					  _this.$message({
						  message: "success！",
						  type: 'success'
					  });
						var data=JSON.stringify({
							name:res.result.name,
							ext:res.result.ext,
							size:res.result.size,
							path:res.result.path,
						})
						_this.visitor.message='mutiFile[' + data+ ']';
					  _this.chatToUser();
					  setTimeout(function () {
						  _this.scrollBottom();
					  },2000);
					}
				})
				.catch(error => {
				  console.error(error);
				});
				});
				document.body.appendChild(input);
				input.click();
			},
            //超时关闭
            checkTimeout:function(){
                var _this=this;
                this.timeTool.timeoutTimer=setInterval(function(){
                    if ((Date.now() - _this.timeTool.activeTime) >= _this.timeTool.timeoutTime) {
                        console.log("访客长时间无回话");
						if(_this.websocket.instance!=null){
							_this.websocket.serverReturnClose=true;
							_this.websocket.instance.close();
						} 
						_this.comment.dialog=true;
                    }
                },10000);
            },
			//富文本渲染文本点击
			htmlBoxClick(e){ 
				let _this=this;
			  if (e.target.nodeName === 'IMG'|| e.target.nodeName == 'img') { //判断是否图片标签
				const img = e.target.currentSrc; //获取点击图片地址
				this.imgPreviewSrc=[img];
				this.$refs.preview.clickHandler();
				return false;
			  }
			  if (e.target.nodeName === 'A'|| e.target.nodeName == 'a') { //判断是否a
					const href = e.target.href.charAt(e.target.href.length - 1);
					console.log(href);
					if(href=="#"){
						let html=e.target.innerHTML;
						_this.visitor.message=html;
						_this.chatToUser();
						e.preventDefault();
						e.stopPropagation();
						return false;
					}
			  }
			},
			 //开始录音
			startRecoder:function(){
				if(this.recorder){
					this.recorder.destroy();
					this.recorder=null;
				}
				var _this=this;
				Recorder.getPermission().then(function() {
					_this.recorder = new Recorder();
					_this.recorderAudio = document.querySelector('#audio');
					_this.recorder.start();
					_this.recorder.onprogress = function (params) {
						_this.recoderSecond = parseInt(params.duration);
						if(_this.recoderSecond>=60) _this.stopRecoder();
					}
				}, function(error){
					_this.$message({
						message: error,
						type: 'error'
					});
					return;
				});
			},
			//结束录音
			stopRecoder:function(){
				if(!this.recorder){
					return;
				}
				var blob=this.recorder.getWAVBlob();
				this.recorderAudio.src = URL.createObjectURL(blob);
				this.recorderAudio.controls = true;
				this.recorderEnd=blob;
				this.recorder.destroy();
				this.recorder=null;
			},
			//发送录音
			sendRecoder:function(){
				this.stopRecoder();
                if(!this.recorderEnd) return;
				
				let _this=this;
				let formData = new FormData();
				formData.append("realfile", this.recorderEnd); //传给后台的file的key值是可以自己定义的
				fetch(_this.ApiHost+'/2/uploadAudio', {
				  method: "POST",
				  body: formData
				})
				.then(response => response.json())
				.then(res => {
				  console.log(res);
					if(res.code!=200){
					  _this.$message({
						  message: res.msg,
						  type: 'error'
					  });
					}else{
					  _this.$message({
						  message: "success！",
						  type: 'success'
					  });
					  _this.cancelRecoder();
					  _this.visitor.message='audio[' + res.result.path+ ']';
					  _this.chatToUser();
					}
				})
				.catch(error => {
				  console.error(error);
				});
			},
			//取消录音
			cancelRecoder:function(){
				this.audioDialog=false;
				if(!this.recorder){
					return;
				}
				this.recorder.destroy();
				this.recorder=null;
				this.recoderSecond=0;
			},
			//录音的百分比
			recoderFormat:function(percentage){
				return percentage+"s";
			},
			//发送评价
			sendComment:function (){
				let _this=this;
				const formData = new FormData();
				formData.append('comment_score', this.comment.score);
				formData.append('comment_content', this.comment.textarea);
				formData.append('kefu_name', this.visitor.to_id);
				formData.append('ent_id', this.visitor.ent_id);
				formData.append('visitor_id', this.visitor.visitor_id);
				fetch(this.ApiHost+'/2/comment', {
					method: 'post',
					body:formData,
				})
				.then((response) => response.json())
				.then((response) => {
					console.log(response);
					var code=response.code;
					var msg=response.msg;
					_this.comment.dialog=false;
					if(code==200){
						_this.$message({
						  message: "success",
						  type: 'success'
						});
					}
				})

			},
			//展示通知
			showTitle:function(title){
				this.msgList.push({
					type:"notice",
					content:title,
				});
				this.scrollBottom();
			},
		},
		mounted: function () {
			this.visitorLogin();
		}
	}
</script>

<style lang="scss">
	.chatAppBody{
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f6;
	}
	.chatElfTitle{
		padding: 5px 0px;
		text-align: center;
		font-size: 14px;
	}
	.chatBox{
		flex: 1;
		padding: 0px 10px;
		padding-bottom: 15px;
		overflow: auto;
	}
	.chatBottom{
		display: flex;
		flex-direction: column;
	}
	.chatElfRow{
		display: flex;
		align-items: self-start;
		margin: 12px 0px;
	}
	.chatAvatar{
		margin-right: 5px;
		flex-shrink: 0;
	}
	.chatUsername {
	    font-size: 12px;
	    white-space: nowrap;
	    color: #666;
	    margin-bottom: 10px;
	}
	.chatElfContent{
		border-radius: 10px;
		padding: 10px;
		background-color: rgb(255,255,255);
		font-size: 15px;
		word-break: break-all;
		line-height: 25px;
		display: inline-block;
		color: #333333;
	}
	.elfCard{
		cursor: pointer;
		padding: 5px;
		border-radius: 2px;
		width: auto;
		max-width: 730px;
		display: flex;
		border-radius: 5px;
	}
	.elfCard img{
		width: 100px;
		height: 100px;
		margin-right: 15px;
	}
	.elfCard .elfCardPrice{
		color: #ff7736;
		font-weight: bold;
		font-size: 16px;
		margin-top: 10px;
	}
	.elfCard .elfCardTitle{
		color: #333;
	}
	.chatElfRowMe{
		justify-content: flex-end;
		align-items: center;
	}
	.chatElfRowMe .chatElfContent{
		background-color: #FFEEE7;
		margin-right: 5px;
	}
	.chatElfNotice{
		text-align: center;
		color: #B6B6B6;
		margin: 8px 0;
		font-size: 12px;
	}
	.chatElfAreaBox .chatSendBtn{
		background: #FF6704;
		padding: 8px 15px;
		color: #fff;
		border-radius: 15px;
		font-size: 13px;
		font-family: PingFang SC;
	}
	.chatElfArea{
		display: flex;
		padding: 3px 5px;
		align-items: center;
		background: #fff;
	}
	.chatElfArea .iconfont{
		color: #7a7a7a;
		font-size: 30px;
		margin: 0px 6px;
		cursor: pointer;
	}
	.chatElfArea .iconfont:hover{
		color: #ff6704;
	}
	.chatElfAreaInput{
		border-radius: 10px;
		border: 0;
		flex: 1;
		outline: none;
		resize: none;
		box-sizing: border-box;
		color: #333333;
		min-height: 50px;
		font-size: 16px;
		padding-top: 15px;
	}
	.chatCopyright{
		color: #999a9b;
		font-size: 12px;
		text-align: center;
		margin-bottom: 10px;
		filter: grayscale(1);
		opacity: .9;
		font-family: Inter,-apple-system,system-ui,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Tahoma,Arial,sans-serif;
	}
	.chatElfExtend{
		border-radius: 0px 0px 10px 10px;
		background: #fff;
		padding: 10px;
		min-height: 200px;
		margin-top: -5px;
	}
	.chatElfExtend .iconExtendBtn{
		width: 60px;
		background: #F5F5F6;
		display: flex;
		height: 60px;
		text-align: center;
		float: left;
		color: #4e4e4e;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 12px;
		margin: 0px 10px 10px 0px;
		border-radius: 10px;
	}
	.chatElfExtend .iconExtendBtn .elIcon{
		font-size:26px;
		color: #4e4e4e;
	}
	.hotQuestions{
		margin-bottom: 5px;
		width: 100%;
		white-space: nowrap;
		overflow-x: auto;
	}
	.hotQuestions a{
		    display: inline-block;
		    margin-left: 10px;
		    border-radius: 20px;
		    cursor: pointer;
		    font-size: 12px;
		    padding: 5px 9px;
		    background: #fff;
		    border: 1px solid #dcdfe6;
		    color: #606266;
	}
	.chatElfContent a{
		color: #07a9fe;
		text-decoration: none;
	}
	.elfMoreMessage{
		display: inline-block;
		word-break: break-all;
		color: #ff6704;
		margin: 0 24px;
		max-width: calc(100% - 48px);
		background-color: #fff;
		border-radius: 16px;
		font-size: 12px;
		padding: 4px 16px;
		cursor: pointer;
	}
	.alink{
		display: inline-block;
		word-break: break-all;
		color: #07a9fe;
		font-size: 12px;
		cursor: pointer;
	}
	.chatSendProduct{
		display: flex;
		background: #fff;
		margin: 2px 10px;
		padding: 10px;
		font-size: 14px;
		border-radius: 10px;
		position: absolute;
		bottom: 85px;
		left: 0;
		right: 0;
		z-index: 999;
		box-shadow: 0 5px 30px rgb(50 50 93 / 8%), 0 1px 3px rgb(0 0 0 / 5%);
	}
	.chatSendProduct .productImg{
		max-width: 80px;
		max-height: 80px;
	}
	.chatSendProduct .productInfo{
		margin: 0 5px;
		flex: 1;
	}
	.chatSendProduct .productPrice{
		color: #ff5000;
		margin-top: 10px;
	}
	.chatSendProduct .productBtns{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
	}
	.chatSendProduct .el-icon-close{
		font-size: 18px;
		cursor: pointer;
	}
	.coverMask{
		position: fixed;
		width: 100%;
		height: 100%;
		background: #fff;
	}
	.coverMask #remoteVideo{
		width: 100%;
		height: 100%;
	}
	.coverMask #remoteAudio{
		width: 100%;
	}
	.comment{
		position: fixed;
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,0.2);
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
	}
	.scoreBox{
		background: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 25px 10px 0px 10px;
		position: relative;
	}
	.scoreBox .commentArea{
		width: 100%;
		margin-top: 40px;
	}
	.scoreBox  .el-textarea__inner{
		border-radius: 10px;
		background: #F5F5F6;
		border: none;
		color: #333333;
	}
	.scoreBox .el-rate__icon{
		font-size: 35px;
		margin: 0 8px;
	}
	.scoreBox .scoreTitle{
		color: #2A2A2A;
		font-family: PingFang SC;
		font-size: 18px;
		margin-top: 15px;
	}
	.scoreBox .scoreDesc{
		color: #666666;
		font-family: PingFang SC;
		font-size: 14px;
		margin-bottom: 20px;
		margin-top: 10px;
	}
	.scoreBox .icon-guanbi{
		position: absolute;
		right: 10px;
		top: 10px;
		font-size: 22px;
		cursor: pointer;
		color: #333;
	}
	.scoreBox .commentBtn{
		display: block;
		width: 100%;
		border-radius: 20px;
		background-color: #FF6704;
		margin: 50px auto 35px auto;
	}
	.emojis{
		background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		height: 160px;
		overflow: auto;
		font-size: 22px;
	}
	.emojis span{
		display: block;
		margin: 5px;
	}
	.chatImagePic {
	    max-width: 150px;
	}
	.dialogRecoder{
	    text-align: center;
	}
	.dialogRecoder .el-button {
	    margin:6px;
	}
	.videoAudioBox{
		width: 100%;
		height: 100%;
		position: fixed;
		z-index: 9999999;
		left: 0px;
		top: 0px;
		background: #333;
	}
	.videoAudioBox .bottomBtns{
		bottom: 60px;
		width: 100%;
		position: fixed;
		text-align: center;
		display: flex;
		justify-content: center;
		flex-direction: row;
		align-items: flex-end;
	}
	.videoAudioBox .refuse{
		display: block;
		width: 55px;
		height: 55px;
		color: #fff;
		background-color: #da4c4b;
		text-align: center;
		line-height: 55px;
		cursor: pointer;
		border-radius: 50%;
	}
	.videoAudioBox #remoteVideo{
		width: 100%;
		height: 100%;
	}
	.videoAudioBox #remoteAudio{
		display: block;
		width: 55px;
		height: 55px;
		border-radius: 50%;
		margin-right: 100px;
	}
	.videoAudioBox #remoteVideoMaskLogo{
		width: 100px;
		height: 100px;
		position: absolute;
		background: #fff;
		border-radius: 12px;
		z-index: 9;
		top: 60px;
		left: 50%;
		transform: translateX(-50%);
	}
	.videoAudioBox #chatRtc{
	    width: 100%;
	    height: 100%;
		display: none;
	}
	.el-message-box{
		width: auto;
		max-width: 100%;
		max-height: 100%;
		overflow: auto;
	}
	</style>